package com.bilibili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bilibili.dao.VideoLikeMapper;
import com.bilibili.domain.entity.Video;
import com.bilibili.domain.entity.VideoLike;
import com.bilibili.domain.exception.ConditionException;
import com.bilibili.service.VideoLikeService;
import com.bilibili.service.VideoService;
import lombok.Data;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author www
* @description 针对表【t_video_like(视频点赞记录表)】的数据库操作Service实现
* @createDate 2024-06-17 15:02:50
*/
@Service
public class VideoLikeServiceImpl extends ServiceImpl<VideoLikeMapper, VideoLike>
    implements VideoLikeService {

    @Resource
    private VideoLikeMapper videoLikeMapper;
    @Resource
    private VideoService videoService;

    LambdaQueryWrapper<VideoLike> wrapper = new LambdaQueryWrapper<>();

    @Override
    public void addVideoLike(Long videoId,Long userId) {
        Video video = videoService.getById(videoId);
        if (video==null){
            throw new ConditionException("非法视频！");
        }
        //查询是否已经点赞
        wrapper.eq(VideoLike::getVideoId,videoId)
                .eq(VideoLike::getUserId,userId);
        VideoLike videoLike = videoLikeMapper.selectOne(wrapper);
        if (videoLike!=null){
            throw new ConditionException("已经点赞过了！");
        }
        //点赞
        videoLike = new VideoLike();
        videoLike.setVideoId(videoId);
        videoLike.setUserId(userId);
        videoLike.setCreateTime(new Date());

        videoLikeMapper.insert(videoLike);
    }

    @Override
    public void deleteVideoLik(Long videoId, Long userId) {
        wrapper.eq(VideoLike::getVideoId,videoId)
                .eq(VideoLike::getUserId,userId);

        videoLikeMapper.delete(wrapper);
    }

    @Override
    public Map<String, Object> getVideoLike(Long videoId, Long userId) {
        //获取该视频点赞总数量
        wrapper.eq(VideoLike::getVideoId,videoId);
        Long count = videoLikeMapper.selectCount(wrapper);

        //查询该登录用户是否对该视频点赞
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VideoLike::getVideoId,videoId)
                .eq(VideoLike::getUserId,userId);
        VideoLike videoLike = videoLikeMapper.selectOne(wrapper);

        boolean like = videoLike!=null?true:false;

        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("like",like);
        return map;
    }
}




